<template>
  <scroll class="order_detail__container">
    <div>
      <div class="order-title base-padding">
        {{ userCarState.driverOrderState[orderState] }}
      </div>
      <div class="order-price base-padding">
        <p>{{estimateText[0]}}总额 ￥{{ setOrderPrice(orderDetailData.totalAmount) }}</p>
        <p @click="onClickFoloedPane" v-show="isShowPriceDetail">
          价格明细&nbsp;&nbsp;
          <icon type="iconfont icon-unfold" size="1.5" :style="handIconSly"/>
        </p>
      </div>
      <div class="order-price__detail"
           ref="order_price__detail"
           :style="handleFoloedPanelSly"
           v-show="isShowPriceDetail">
        <div class="detail__list" v-for="(item, index) in feeDetailData" :key="index">
          <p class="detail__label">{{ item.type }}</p>
          <span class="gutter__line"></span>
          <p class="datail__price">¥{{ item.amount }}</p>
        </div>
      </div>
      <div class="order-apply base-padding" v-show="!disabledApplyBtn">
        <x-button class="btn" @click.native="onClickCloseOrder" v-if="isShowCloseOrder" :disabled="isOrderDisabled">取消订单</x-button>
        <x-button class="btn" @click.native="onClickGoPay" v-if="isShowPay">去支付</x-button>
      </div>
      <div class="order-info base-padding">
        <div class="user">
          <div class="avatar">
            <!--<img src="">-->
          </div>
          <div class="info">
            <p>
              <span>{{ tripDetailData.driverName ? tripDetailData.driverName : '不详' }}</span>
              <small>{{ tripDetailData.vehicleNo ? tripDetailData.vehicleNo : 'xxxxx' }}</small>
            </p>
            <p>{{ tripDetailData.vehicleColor }} {{ tripDetailData.vehicleBrand }}</p>
          </div>
          <a :href="'tel:' + tripDetailData.driverTel">
            <icon class="icon" type="icon-phone" size="3"></icon>
          </a>
        </div>
        <div class="from">
          <p>
            <span>[出发地]</span>
            <span class="time">{{ tripDetailData.carUserTime | filterFormatTime }}</span>
          </p>
          <p>
            <span>{{ tripDetailData.startName }}</span>
            <span>{{ tripDetailData.startAddress }}</span>
          </p>
        </div>
        <div class="to">
          <p>
            <span>[目的地]</span>
            <span class="time">{{ tripDetailData.carEndTime | filterFormatTime }}</span>
          </p>
          <p>
            <span>{{ tripDetailData.endName }}</span>
            <span>{{ tripDetailData.endAddress }}</span>
          </p>
        </div>
        <div class="desc">
          {{estimateText[1]}}时长{{ tripDetailData.actualTimeLength }}分钟，行驶{{ tripDetailData.drivingKilometres }}公里
        </div>
      </div>
      <!-- 订单号 -->
      <sl-group-item titleLeft="订单号">
        <div slot="slotTitleRight">
          <span>{{ orderDetailData.id }}</span>
          <small>2017/12/18 15:30</small>
        </div>
      </sl-group-item>
      <!-- 支付方式 -->
      <sl-group-item titleLeft="支付方式" :titleRight="userCarState.userCarPayWay[orderDetailData.paymentMethod]"/>
      <!-- 支付时间 -->
      <sl-group-item titleLeft="支付时间" :titleRight="orderDetailData.paymentDate" v-show="orderDetailData.paymentDate"/>
      <!-- 费用归属 -->
      <sl-group-item titleLeft="费用归属" :titleRight="orderDetailData.costUnitName"/>
      <!-- 出行类别 -->
      <sl-group-item titleLeft="出行类别" :titleRight="orderDetailData.travelName"/>
      <!-- 附加信息 -->
      <sl-title title="附加信息" v-show="orderDetailData.remark !== ''"/>
      <sl-group-item v-show="orderDetailData.remark !== ''" :titleLeft="orderDetailData.remark"/>
    </div>
  </scroll>
</template>

<script type="text/ecmascript-6">
import { mapState } from 'vuex';
import { TransferDom, Popup, Group, XButton } from 'vux'
import slGroupItem from './modules/sl-group-item/sl-group-item'
import slTitle from './modules/sl-title/sl-title'
import { car } from '../data'
let timer = null
export default {
  components: { slGroupItem, slTitle, Popup, Group, XButton },
  data () {
    return {
      disabledApplyBtn: false,
      orderPriceDetailStatus: false,
      paymentStatus: '',
      orderState: '',
      orderDetailData: {},
      feeDetailData: [],
      tripDetailData: {},
      estimateText: ['预估', '预估'],
      isShowCloseOrder: false,
      isShowPay: false,
      isShowPriceDetail: false,
      isOrderDisabled: false
    }
  },
  created () {
    this.getDriverState();
    this._getOrderDetails();
  },
  filters: {
    // 格式化时间 时:分
    filterFormatTime (time) {
      if (time) {
        return moment(time).format('MM:DD')
      }
      return ''
    }
  },
  computed: {
    ...mapState([
      'userCarState'
    ]),
    handIconSly () {
      return {
        transform: this.orderPriceDetailStatus ? 'rotate(180deg)' : 'rotate(0)',
        transition: 'all .5s'
      }
    },
    handleFoloedPanelSly () {
      let _height = '0'
      if (this.$refs.order_price__detail || this.feeDetailData.length > 0) {
        _height = this.$refs.order_price__detail.scrollHeight
      }
      return {
        height: !this.orderPriceDetailStatus ? '0' : `${_height}px`
      }
    }
  },
  methods: {
    onClickCloseOrder () {
      let self = this;
      this.$vux.confirm.show({
        content: '是否确认取消订单',
        onConfirm () {
          self._isNeedFine()
        }
      })
    },
    onClickGoPay () {
      this.$router.push({
        name: 'pay',
        query: {
          orderId: this.$route.params.orderId
        }
      });
    },
    _isNeedFine () {
      car.needFine({
        orderId: `${this.$route.params.orderId}`
      }).then((res) => {
        if (res.data.code === 0) {
          if (res.data.data) {
            this.$router.push({
              path: `/carIndex/orderError/${this.$route.params.orderId}`,
              query: {
                state: 2
              }
            })
          } else {
            this._cancelOrder();
          }
        } else {
          this.$vux.toast.show({
            time: 1000,
            type: 'warn',
            text: res.data.msg,
            position: 'middle'
          })
        }
      });
    },
    _cancelOrder () {
      let state = 0;
      car.cancelOrder({
        orderId: this.$route.params.orderId,
        reason: '任性',
        force: false
      }).then(res => {
        if (res.data.code === 0) {
          if (res.data.data && res.data.data > 0) {
            state = 2
          }
          this.$router.push({
            path: `/carIndex/orderError/${this.$route.params.orderId}`,
            query: {
              state: state
            }
          })
        } else {
          this.$vux.toast.show({
            time: 1000,
            type: 'warn',
            text: res.data.msg,
            position: 'middle'
          })
        }
      })
    },
    onClickFoloedPane () {
      this.orderPriceDetailStatus = !this.orderPriceDetailStatus
    },
    _getOrderDetails () {
      car.getOrderDetails({
        orderId: this.$route.params.orderId
      }).then((res) => {
        if (res.data.code === 0) {
          this.orderDetailData = res.data.data.order
          this.tripDetailData = res.data.data.trip
          if (res.data.data.feeDetail) {
            this.feeDetailData = res.data.data.feeDetail
          }
        }
      })
    },
    // 轮询司机订单状态
    getDriverState () {
      let STOP_NEXT = ['DRIVE_OVER', 'WAIT_PAY', 'CANCELED'];
      car.receiveOrder({
        orderId: this.$route.params.orderId
      }).then(res => {
        if (res.data.code === 0) {
          this.orderState = res.data.data.status;
          let _isNext = STOP_NEXT.findIndex(a => a === res.data.data.status);
          if (_isNext === -1) {
            setTimeout(() => {
              this.getDriverState();
            }, 5000);
          }
        } else {
          this.$vux.toast.show({
            time: 3000,
            type: 'warn',
            text: reject,
            position: 'middle'
          });
          clearInterval(timer)
        }
      });
    },
    setOrderPrice (price) {
      if (!price) {
        let localPrice = store.get('USER_CAR_TYPE_DATA');
        return !localPrice ? '' : localPrice.price
      }
      return price
    }
  },
  watch: {
    orderState () {
      const HIDE_CLOSE_ORDER_BTN = ['WAIT_PAY', 'CANCELED', 'DRIVE_OVER'];
      if (HIDE_CLOSE_ORDER_BTN.findIndex(a => a === this.orderState) === -1) {
        this.isShowCloseOrder = true
      } else if (this.orderState === 'WAIT_PAY') {
        this.isShowPay = true;
        this.isShowPriceDetail = true;
        this.isShowCloseOrder = false;
        this._getOrderDetails();
      } else {
        this.isShowPriceDetail = true;
        this.isShowCloseOrder = false;
        this.isShowPay = false;
      }
      if (this.orderState === 'DRIVE_OVER') {
        this.isShowPriceDetail = true;
        this._getOrderDetails();
      }
    }
  },
  beforeRouteLeave (to, from, next) {
    clearInterval(timer);
    next()
  },
  directives: {
    TransferDom
  }
}
</script>
<style>

</style>

<style lang="stylus" type="text/stylus" scoped>
  @import "~assets/css/theme"
 .order_detail__container
   position: absolute;
   left: 0;
   right: 0;
   top: 0;
   bottom: 0;
   overflow: hidden;
   background $sl_theme_bg
   .order-title
     font-size 20px
     background #46a1bb
     padding-top 1.5 * .61rem
     padding-bottom 1.5 * .61rem
     color #fff
   .order-price
     display flex
     justify-content space-between
     background #fff
     padding-top 1 * .61rem
     padding-bottom 1 * .61rem
     font-size 14px
   .order-price__detail
     background: #f2f2f2
     overflow hidden
     transition all .5s
     .detail__list
       display flex
       justify-content space-between
       align-items center
       font-size $sl_font_size_small
       padding .5 * .61rem 2 * .61rem
       .detail__label
         width 20%
       .gutter__line
         border-top 1px #000 dashed
         width 60%
       .detail__label
         width 20%
   .order-apply
     padding-top 1 * .61rem
     text-align center
     font-size 16px
     .btn
       background #fff
       border 1px #75b9cc solid
       color #43a0ba
   .order-info
     margin 15px 0
     .user
       padding 1 * .61rem
       display flex
       justify-content space-between
       align-items center
       background #fff
       border-bottom 1px #f7f9fb solid
       .avatar
         width 40px
         height 40px
         background url("../assets/images/img1.png") no-repeat center center
         background-size contain
         border-radius 50%
         overflow hidden
         img
           width 100%
           height 100%
       .info
         width 80%
         padding-left 10px
         p
           line-height 20px
           font-size $sl_font_size_small
           &:nth-child(1)
             span:nth-child(1)
               font-size 14px
             small
               background #786d84
               color #fff
               padding 2px 12px
               font-size 1 * .61rem
               margin-left 10px
     .from, .to
       padding 1 * .61rem
       background #fff
       border-bottom 1px #f7f9fb solid
       line-height 24px
       display flex
       >p
         display flex
         align-content space-between
         flex-wrap wrap
         span
           width 100%
           font-size $sl_font_size_small
         &:nth-child(1)
           width 25%
           position relative
           padding-left 2 * .61rem
           :not(.time)
             color $sl_theme_title
             font-size $sl_font_size_small
         &:nth-child(2)
           width 50%
           span
             font-size $sl_font_size_small
             text-overflow ellipsis
             -webkit-line-clamp 1
             white-space nowrap
             overflow hidden
             &:nth-child(2)
               color $sl_font_color_desc
               font-size $sl_font_size_small
       &.from
         p:nth-child(1)::before
           content ''
           display block
           position absolute
           top 50%
           left 0
           transform translateY(-50%)
           width 1 * .61rem
           height 1 * .61rem
           background $sl_place_from
           border-radius 50%
       &.to
         p:nth-child(1)::before
           content ''
           display block
           position absolute
           top 50%
           left 0
           transform translateY(-50%)
           width 1 * .61rem
           height 1 * .61rem
           background $sl_place_to
           border-radius 50%
     .desc
       padding 2 * .61rem 0
       background #fff
       text-align center
       font-size $sl_font_size_14
   .list
     display flex
     justify-content space-between
     align-items center
     padding 15px
     background #fff
     border-bottom 1px #ddd solid
     .item
       font-size 1.4 * .61rem
       p, small
         display block
         text-align right
         line-height 24px
       small
         color $font_color_bg
</style>
